<?php

namespace app\home\controller;

use app\common\controller\Home;

class Collect extends Home
{
    public function __construct()
    {
        parent::__construct();

        $this->CollectModel = model('User.Collect');
    }

    public function collect()
    {
        if($this->request->isAjax())
        {
            $postid = $this->request->param('postid',0);

            $userid = isset($this->LoginUser['id']) ? $this->LoginUser['id'] : 0;

            $collect = $this->CollectModel->where(['userid' => $userid,'postid' => $postid])->find();

            if($collect)
            {
                // 取消收藏
                $result = $this->CollectModel->destroy($collect['id'],true);

                if($result === FALSE)
                {
                    $this->error('取消收藏失败');
                }else{
                    $this->success('已取消');
                }

            }else{
                // 收藏
                $data = [
                    'userid' => $userid,
                    'postid' => $postid
                ];

                $result = $this->CollectModel->validate('common/User/Collect')->save($data);

                if($result === FALSE)
                {
                    $this->error('收藏失败');
                }else{
                    $this->success('收藏成功');
                }
            }
        }
    }
}
